using System.Collections.Generic;
using Ninject;
using RentalOfCars.Domain.Entities;
using RentalOfCars.Server.Domain.ClientServerInterface;

namespace RentalOfCars.Client.Presentation
{
    public class AddClientWindowPresenter
    {
        private readonly IDbAccessSession _session;
        private readonly IAddClientWindowView _view;
        private readonly IKernel _kernel;
        private IList<IDiscount> _discounts;

        public AddClientWindowPresenter(IAddClientWindowView view, IDbAccessSession session, IKernel kernel)
        {
            _view = view;
            _kernel = kernel;
            _session = session;

            _view.OnOk = OnOk;

            UpdateAvailableDiscounts();
        }

        private void UpdateAvailableDiscounts()
        {
            _discounts = _session.GetDiscounts();
            var ds = new int[_discounts.Count];
            for (int i = 0; i < _discounts.Count; i++)
            {
                ds[i] = _discounts[i].Value;
            }

            _view.AvailableDiscounts = ds;
        }

        private void OnOk()
        {
            string name = _view.ClientName;
            string lastName = _view.ClientLastName;
            string patronymic = _view.Patronymic;
            string passport = _view.Passport;
            string phone = _view.Phone;
            int selectedDiscount = _view.SelectedDiscountIndex;
            if (selectedDiscount == -1)
            {
                var messenger = _kernel.Get<IMessenger>();
                messenger.ShowError("You must select discount.");
                return;
            }

            var client = new Infrastructure.Entities.Client(0, name, lastName, patronymic, passport, phone, 0, _discounts[selectedDiscount]);
            _session.AddClient(client);

            _view.CloseWindow();
        }
    }
}